
import { getEmployeeInfo } from '@/api/employeeApi'

export default {
    data() {
        return {
            // 数据相关
            rawData: [],
            employeeMap: new Map(),  // 员工信息缓存 {employeeId: name}
            operatorMap: new Map(),   // 处理人信息缓存 {operatorId: name}

            // 状态相关
            loading: false,
            isAdmin: false,
            currentUserId: null,

            // 查询参数
            queryForm: {
                dateRange: [],
                status: null
            },

            // 配置项
            statusOptions: [
                { value: 0, label: '待处理' },
                { value: 1, label: '已批准' },
                { value: 2, label: '已拒绝' }
            ],
            statusTextMap: {
                0: '待处理',
                1: '已批准',
                2: '已拒绝'
            },
            statusTagMap: {
                0: 'warning',
                1: 'success',
                2: 'danger'
            }
        }
    },

    computed: {
        // 处理后的表格数据
        processedData() {
            return this.rawData
                .filter(record => this.filterByPermission(record))
                .filter(record => this.filterByStatus(record))
                .filter(record => this.filterByDate(record))
        }
    },

    async mounted() {
        await this.initialize()
    },

    methods: {
        // 初始化系统
        async initialize() {
            await this.loadCurrentUser()
            await this.loadData()
        },

        // 加载当前用户信息
        async loadCurrentUser() {
            try {
                const empId = sessionStorage.getItem('empId')
                if (!empId) {
                    this.$message.error('未检测到登录信息')
                    return this.$router.push('/login')
                }

                const res = await getEmployeeInfo(empId)
                if (res.code === 200) {
                    const user = res.data
                    this.isAdmin = user.departmentId === 3 && user.role === 1
                    this.currentUserId = user.employeeId
                }
            } catch (error) {
                console.error('用户信息加载失败:', error)
                this.$router.push('/login')
            }
        },

        // 加载核心数据
        async loadData() {
            try {
                this.loading = true
                await this.loadLeaveRecords()
                await this.loadEmployeeDetails()
            } catch (error) {
                this.$message.error('数据加载失败')
            } finally {
                this.loading = false
            }
        },

        // 加载请假记录
        async loadLeaveRecords() {
            try {
                const params = {
                    employeeId: this.currentUserId,
                    status: this.queryForm.status
                }

                if (this.queryForm.dateRange?.length === 2) {
                    params.startDate = this.queryForm.dateRange[0]
                    params.endDate = this.queryForm.dateRange[1]
                }

                const res = await this.$http.get('/leave/records', { params })
                if (res.data.code === 200) {
                    this.rawData = res.data.data || []
                }
            } catch (error) {
                throw new Error('请假记录加载失败')
            }
        },

        // 加载员工详细信息
        async loadEmployeeDetails() {
            const ids = new Set()

            // 收集所有需要查询的ID
            this.rawData.forEach(record => {
                if (record.employeeId) ids.add(record.employeeId)
                if (record.operator && record.operator !== 0) ids.add(record.operator)
            })

            // 批量查询
            await Promise.all(Array.from(ids).map(async id => {
                if (!this.employeeMap.has(id)) {
                    try {
                        const res = await getEmployeeInfo(id)
                        if (res.code === 200) {
                            this.employeeMap.set(id, res.data.employeeName)
                            this.operatorMap.set(id, res.data.employeeName)
                        }
                    } catch (error) {
                        console.warn(`员工${id}信息加载失败:`, error)
                    }
                }
            }))
        },

        // 处理审批操作
        async handleProcess(registrationId, status) {
            this.loading = true;
            try {
                const res=await this.$http.put(
                    `/leave/process/${registrationId}?status=${status}&operatorId=${this.currentUserId}`
                );
                if (res.data.code === 200) {
                    this.$message.success('操作成功');
                    await this.loadData();
                    this.rawData = [...this.rawData]; // 创建新数组触发响应式
                }
            } catch (error) {
                this.$message.error(`操作失败: ${error.response?.data?.message || '未知错误'}`);
            } finally {
                this.loading = false;
            }
        },

        // 过滤方法
        filterByPermission(record) {
            return this.isAdmin
                ? record.operator === this.currentUserId
                : record.employeeId === this.currentUserId
        },

        filterByStatus(record) {
            return this.queryForm.status === null ||
                record.status === this.queryForm.status
        },

        filterByDate(record) {
            if (!this.queryForm.dateRange?.length) return true
            const [start, end] = this.queryForm.dateRange
            const recordDate = new Date(record.startDataLeave).getTime()
            return recordDate >= new Date(start).getTime() &&
                recordDate <= new Date(end).getTime()
        },

        // 日期格式化
        formatDate(dateStr) {
            try {
                return new Date(dateStr).toLocaleDateString('zh-CN')
            } catch {
                return '无效日期'
            }
        },

        // 重置查询
        resetQuery() {
            this.queryForm = {
                dateRange: [],
                status: null
            }
            this.loadData()
        },

        // 处理查询
        handleSearch() {
            this.loadData()
        },
        printEmptyAnnualLeaveCSV() {
            // 1. 创建CSV内容（包含BOM头解决中文乱码）
            const csvContent = "\uFEFF年休假申请记录\n\n";

            // 2. 创建CSV表头
            const headers = [
                "员工ID",
                "员工姓名",
                "部门",
                "申请日期",
                "开始日期",
                "结束日期",
                "休假天数",
                "休假类型",
                "休假原因",
                "审批状态",
                "审批人",
                "备注"
            ].join(",") + "\n";

            // 3. 创建Blob对象
            const blob = new Blob([csvContent + headers], {
                type: 'text/csv;charset=utf-8;'
            });

            // 4. 创建下载链接
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.href = url;

            // 5. 设置文件名（使用当前年月日）
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            link.setAttribute('download', `年休假申请记录_${year}${month}${day}.csv`);

            // 6. 触发下载
            document.body.appendChild(link);
            link.click();

            // 7. 清理
            setTimeout(() => {
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
            }, 100);
        }
    }
}
